package com.zzsz.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Classname AliyunOSSUtil
 * @Description
 * @Date 2025/9/4 13:54
 * @Created by SYL
 */


public class AliyunOSSUtil {

    /**
     * 上传文件
     * MultipartFile file：上传的文件对象,是springmvc上传文件的对象
     */
    public static String upload(MultipartFile file) {
        System.out.println("------OSS文件上传开始--------" );

        // 阿里云OSS配置信息
        String endPoint = AliyunOSSConstants.END_POINT;
        String accessKeyId = AliyunOSSConstants.ASSCESS_KEY_ID;
        String accessKeySecret = AliyunOSSConstants.ASSCESS_KEY_SECRET;
        String bucketName = AliyunOSSConstants.BUCKET_NAME;
        String fileDir = AliyunOSSConstants.FILE_DIR;

        // 最终文件路径
        String fileUrl = null;
        // 根据上面配置信息，创建OSS客户端
        com.aliyun.oss.OSS client = new OSSClientBuilder( ).build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 获取文件对象的原始名称
            String originalFilename = file.getOriginalFilename( );
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            // 获取当前日期,当做文件路径的一部分,即根据日期存放文件
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date( ));
            // 设置文件路径和名称
            fileUrl = fileDir + "/" + (dateStr + "/" + UUID.randomUUID( ).toString( ).replace("-", "") + suffix);
            System.out.println("最终文件路径fileUrl：" + fileUrl);
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file.getInputStream( )));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                System.out.println("resp：" + result);
                System.out.println("------OSS文件上传成功------" + AliyunOSSConstants.COMMON_URL + fileUrl);
            }
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace( );
        } finally {
            if (client != null) {
                client.shutdown( );
            }
        }
        // 想办法自己存储到数据库中
        // 不要再这里存储
        // 这里是返回文件的url
        System.out.println("------OSS文件上传结束--------" );
        System.out.println("文件路径是什么：" + fileUrl);
        return fileUrl;
    }

    /**
     * 删除文件
     */
    public static String delete(String fileUrl) {
        System.out.println("------OSS文件删除开始--------" + fileUrl);

        String endPoint = AliyunOSSConstants.END_POINT;
        String accessKeyId = AliyunOSSConstants.ASSCESS_KEY_ID;
        String accessKeySecret = AliyunOSSConstants.ASSCESS_KEY_SECRET;
        String bucketName = AliyunOSSConstants.BUCKET_NAME;
        OSS client = new OSSClientBuilder( ).build(endPoint, accessKeyId, accessKeySecret);
        try {
            ((OSS) client).deleteObject(bucketName, fileUrl);
            System.out.println("------OSS文件删除成功------" + AliyunOSSConstants.COMMON_URL + fileUrl);
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } finally {
            if (client != null) {
                client.shutdown( );
            }
        }
        return AliyunOSSConstants.COMMON_URL + fileUrl;
    }
}
